<?php
/***************************************************************************
 * 
 * Copyright (c) 2010 , Inc. All Rights Reserved
 * $Id$:hapn.php,2010/05/07 13:57:27 
 * 
 **************************************************************************/
 
 
 
/**
 * @file ToolApp.php
 * @author huqingping
 * @date 2010/05/07 13:57:27
 * @version 1.0 
 * @brief 
 *  
 **/

require_once FR_ROOT.'core/ToolBase.php';

final class ToolApp extends BaseApp
{
	var $params;
	function __construct($params)
	{
		parent::__construct(); 
		$this->mode = 'tool';
		$this->params = $params;
	}
	
	function init()
	{
		parent::init();
		//加载Cache模块
		require_once LIB_ROOT.'com/Com.php';
		$conf = Conf::get('hapn.com');
		if ($this->debug) {
			$conf['log_func'] = 'Logger::debug';
		}
		Com::init($conf);
	}

	function getClassAndOptions()
	{
		$params = $this->params;
		$mod = array_shift($params);
		$options = $params;
		if (in_array('-d',$options)) {
			//看是否设置了debug选项
			$this->debug = true;
			$options = array_merge(array_diff($options,array('-d')));
		}
		$class = $mod;
		$path = TOOL_ROOT.$class.'.php';
		if (($pos = strpos($mod,'=')) > 0) {
			$class = substr($mod,0,$pos);
			$path = substr($mod,$pos+1);
			if (strncmp($path,'/',1) !== 0) {
				//如果不以/开始，则把查找相对路径
				$path = TOOL_ROOT.$path;
			}
			if (!is_readable($path)) {
				throw new Exception("hapn.u_toolmissclass class $class not found in $path ");
			}
		} elseif (!is_readable($path)) {
			$path = TOOL_ROOT.strtolower($class)."/$class.php";
		}
		if (is_readable($path)) {
			require_once $path;
		}

		if (!class_exists($class)) {
			throw new Exception("mod $class doesn't exist");
		}
		Logger::trace('toolapp hit class=%s path=%s',$class,$path);
		return array($class,$options);
	}

	function process()
	{
		list($class,$options) = $this->getClassAndOptions();
		Logger::trace('toolapp execute with options=%s',serialize($options));
		//自动加载一个配置
		Conf::load(CONF_ROOT.strtolower($class).'.conf.php');
		$tool = new $class();
		$tool->before($this,$options);
		try {
			$tool->execute($this,$options);
		}catch(Exception $ex) {
			$tool->after($this,$options);
			throw $ex;
		}
		$tool->after($this,$options);
	}

	function errorHandler()
	{
		$error = func_get_args();
		if (false === parent::errorHandler($error[0],$error[1],$error[2],$error[3])) {
			return;
		}
		if (true === $this->debug) {
			unset($error[4]);
			print_r($error);
		}
		exit;
	}

	function exceptionHandler($ex)
	{
		parent::exceptionHandler($ex);
		if (true === $this->debug) {
			print_r($ex->__toString());
		}
		exit;
	}

	function shutdownHandler()
	{
		global $__HapN_appid;
		$basic = array('logid'=>$this->appId.'-'.($__HapN_appid-$this->appId));
		Logger::addBasic($basic);
		parent::shutdownHandler();
	}
}




/* vim: set ts=4 sw=4 sts=4 tw=100 noet: */